import Vue from 'vue'
import Layout from '../views/Layout.vue'
import Article from '../views/Article.vue'
import Like from '../views/Like.vue'
import Collect from '../views/Collect.vue'
import User from '../views/User.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'

// # 2、引入VueRouter插件
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// # 3、安装注册
Vue.use(VueRouter)
// # 4、创建路由实例对象
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/article' },
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/article', component: Article },
        { path: '/collect', component: Collect },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    }
  ]
})

// 设置白名单
const WhiteList = ['/login', '/register', '/article']
// 设置路由前置守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  // 判断是否有Token
  if (token) {
    next()
  } else {
    // 判断去的页面是否在白名单
    if (WhiteList.includes(to.path)) {
      next()
    } else {
      next('/register')
    }
  }
})

export default router
